<template>
  <div class="full-height bg-white page-content content relative-position">
    <div class="flex-1 scroll-y scrollbar padding-l-20 padding-r-20 margin-t-20 full-width margin-b-20" style="max-height: calc(100% - 82px)">
      <div class="font-size-16 text-primary padding-b-20" style="line-height: 1">基本信息</div>
      <div class="">
        <detail-dialog :headList="headList" :detailData="orderInfo" :col-number="3" class="font-size-14"/>
      </div>
      <div class="font-size-16 text-primary padding-b-20" style="line-height: 1">报检操作</div>
      <div class="form-inline flex items-center justify-between" style="padding: 0;">
        <q-select
          v-model="shiftId"
          :options="shiftOpt"
          style="width: 25%"
          dense
          :rules="[ val => val !== null || `请选择加工班次`]"
          options-dense
          emit-value
          map-options
          outlined
        >
          <template v-slot:no-option>
            <div class="no-option" />
          </template>
          <template v-slot:before>
            <label class="text-right name label-width font-size-16 text-black">
              <span class="text-red">*</span>
              <span>加工班次:</span>
            </label>
          </template>
        </q-select>
      </div>
      <q-table
        :data="detailTable"
        :columns="detailColumns"
        row-key="number"
        id="table"
        class="myTable scroll inherit stick-last-row"
        :pagination.sync="pagination"
        style="max-height: 500px;margin: 0"
        :hide-bottom="!!detailTable.length"
      >
        <template v-slot:body-cell-count="props">
          <q-td :props="props" :style="{'padding-top': props.row.isSum ? '0' : '20px'}">
            <q-input
              style="width: 120px"
              ref="jobCount"
              v-if="!props.row.isSum"
              v-model="props.row.count"
              maxlength="6"
              mask="######"
              dense
              outlined
              :rules="[
            val => /^\d*$/.test(val) || '只能输入正整数',
            val => Number(val) !== 0 || '只能输入正整数',
            val => judgeCount(val) || '请输入有效报检数量'
          ]"/>
          </q-td>
        </template>
      </q-table>
    </div>
    <div class="dialog-footer text-center padding-b-20 absolute-bottom-left full-width" style="border-top: 1px solid #d3d3d3;padding-top: 10px">
      <q-btn
        outline
        label="返回"
        color="primary"
        @click="onBcak"
        class="qa-btn margin-r-20"
      />
      <q-btn
        label="确认"
        color="primary"
        @click="_workOrderTestSubmit"
        class="qa-btn margin-r-20"
      />
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import storage from 'good-storage'
import { checkinShifts, getOrderDetail, workOrderTest } from '../../boot/job/process-order'
import BACKMIXIN from 'src/components/basic-mixins/back-mixin'

export default {
  name: 'order-test',
  mixins: [BACKMIXIN],
  data () {
    return {
      paramsBuffer: {}, // 缓存区
      headList: {
        deviceName: '加工设备',
        operator: '作业人员',
        processName: '加工工序'
      },
      orderInfo: {
        deviceName: '--',
        operator: '--',
        processName: '--'
      },
      pagination: {
        rowsPerPage: 0
      },
      // 表格头部数据
      detailColumns: [
        { label: '加工产品', align: 'left', field: 'productNameNumber', name: 'productNameNumber' },
        { label: '加工工序', align: 'left', field: 'processSort', name: 'processSort' },
        { label: '订单号', align: 'left', field: 'orderNumber', name: 'orderNumber' },
        { label: '批次号', align: 'left', field: 'orderBatch', name: 'orderBatch' },
        { label: '派工数量', align: 'left', field: 'jobCount', name: 'jobCount' },
        { label: '完工数量', align: 'left', field: 'finishedCount1', name: 'finishedCount1' },
        { label: '不良数量', align: 'left', field: 'defectiveCount1', name: 'defectiveCount1' },
        { label: '待报检数', align: 'left', field: 'defectiveCount', name: 'defectiveCount' },
        { label: '已报检数', align: 'left', field: 'finishedCount', name: 'finishedCount' },
        { label: '该班待报检数', align: 'left', field: 'defectiveCount2', name: 'defectiveCount2' },
        { label: '报检数量', align: 'left', field: 'count', name: 'count' }
      ],
      detailTable: [],
      shiftId: null,
      shiftOpt: [] // 报工班制
    }
  },
  computed: {
    toBeReported () {
      return (this.form.finishedCount - (this.form.qualityControlledCount || 0)).toFixed(1)
    },
    // 当班未报检
    shiftUnreported () {
      const shift = this.shiftOpt.find(v => v.value === this.shiftId)
      const shiftUnreported = shift ? shift.unreported : 0
      return shiftUnreported
    }
  },
  watch: {
    shiftId (val) {
      this.form.count = Math.ceil(this.shiftUnreported)
    }
  },
  methods: {
    initParams (params) {
      this.paramsBuffer = _.cloneDeep(params)
      this.orderInfo.processName = params.processName
      this.orderInfo.operator = params.operator
      this.getOrderDetail(params.id)
      this.checkinShifts(params.id)
    },
    // 获取工单详情
    getOrderDetail (id) {
      this.$q.loading.show()
      // const res = dispatch.getOrderDetail()
      getOrderDetail(id).then(res => {
        let tableData = []
        this.orderInfo.deviceName = `${this.$utils.label(res.deviceName)}(${this.$utils.label(res.deviceNumber)})`
        if (res.workOrders.length) {
          res.workOrders.forEach(item => {
            item.productNameNumber = `${this.$utils.label(item.materialName)}(${this.$utils.label(item.materialNumber)})`
            item.processSort = `${item.processSort + 1}-${this.$utils.label(item.processName)}`
            item.orderNumber = this.$utils.label(item.orderNumber)
            item.orderBatch = this.$utils.label(item.orderBatch)
            item.jobCount = this.$utils.label(item.jobCount)
            item.finishedCount = this.$utils.label(item.finishedCount)
            item.defectiveCount = this.$utils.label(item.defectiveCount)
          })
          tableData = _.cloneDeep(res.workOrders)
          const jobCount = _.sumBy(res.workOrders, 'jobCount')
          const finishedCount = _.sumBy(res.workOrders, 'finishedCount')
          const defectiveCount = _.sumBy(res.workOrders, 'defectiveCount')
          tableData.push({
            productNameNumber: '合计',
            jobCount: jobCount,
            finishedCount: finishedCount,
            defectiveCount: defectiveCount,
            isSum: true
          })
        }
        this.detailTable = tableData
      }).finally(() => {
        this.$q.loading.hide()
      })
    },
    // 获取报工班制
    checkinShifts (id) {
      checkinShifts(id).then(res => {
        if (res.data.length) {
          this.shiftOpt = res.data.map(item => {
            const unreported = (item.checkinCount - item.qcCount).toFixed(1)
            return {
              label: item.name,
              value: item.id,
              unreported: unreported <= 0 ? 0 : unreported// 未报检
            }
          })
          this.shiftId = res.data[0].id
          // this.form.count = Math.ceil(res.data[0].checkinCount - res.data[0].qcCount) // 未报检
        } else {
          this.shiftOpt = []
          this.shiftId = null
          // this.form.count = null
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 工单报检提交
    _workOrderTestSubmit (form, shiftId) {
      const query = {
        shiftId: shiftId,
        count: form.count,
        workOrderId: form.id
      }

      workOrderTest(query).then(res => {
        if (res.code === '1200') {
          this.getList()
          this.workOrderTestDialog.show = false
          this.$message.success('报检成功')
        }
      }).finally(() => {
        this.$refs.workOrderTest.hideLoading()
      })
    },
    // 校验数量
    judgeCount (val) {
      // 报检数量 <= 当班待报检数(向上取整)
      return val <= Math.ceil(this.shiftUnreported)
    },
    onBcak () {
      this.goPath('complete-order', '/main/craft/process-order')
    }
  },
  beforeRouteEnter (to, from, next) {
    to.name === 'orderTest' && next(vm => {
      from.name === 'processOrder' && vm.initParams(vm.$route.params)
      from.name === null && vm.initParams(storage.get('orderTest'))
      storage.remove('orderTest')
    })
  },
  mounted () {
    window.addEventListener('beforeunload', e => {
      this.$route.name === 'orderTest' && storage.set('orderTest', this.paramsBuffer)
    })
  }
}
</script>

<style scoped lang="stylus">
>>>.q-field__bottom{
  padding: 4px 12px;
}
</style>
